<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>教师端 - 课堂管理</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.3/dist/chart.umd.min.js"></script>
    <style>
        body { font-family: 'Arial', sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; }
        .content-wrapper {
            display: flex;
            gap: 20px;
        }
        .question-container {
            flex: 2;
        }
        .chart-container {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        .chart-controls {
            margin-bottom: 10px;
        }
        .toolbar { display: flex; gap: 10px; margin: 20px 0; }
        .button { padding: 8px 16px; background-color: #2196F3; color: white; border: none; border-radius: 4px; cursor: pointer; }
        .question-box { border: 1px solid #ddd; padding: 20px; margin-bottom: 20px; }
        .stats-box { border: 1px solid #4CAF50; padding: 20px; }
    </style>
</head>
<body>
    <div class="toolbar">
        <button class="button" id="publishBtn" onclick="publishQuestion()">发布题目</button>
        <button class="button" id="nextBtn" onclick="nextQuestion()">下一题</button>
        <!-- <button class="button" onclick="socket.emit('requestStats')">检查数据一致性</button> -->
        <button class="button" onclick="sendToolLink()">发送计算工具</button>
        <!-- 新增三个链接按钮 -->
        <button class="button" onclick="window.open('/生日概率计算原理.html')">概率计算原理</button>
        <button class="button" onclick="window.open('/生日概率模拟实验.html')">概率模拟实验</button>
        <button class="button" onclick="window.open('/生日匹配展示.html')">生日匹配展示</button>
        <!-- <button class="button" onclick="window.open('/teacher_program_show.html')">教师端程序展示界面</button> -->
        
    </div>

    <div class="content-wrapper">
        <div class="question-container">
            <div class="question-box" id="currentQuestionDisplay"></div>
        </div>
        <div class="chart-container">
            <div class="chart-controls">
                <button class="button" id="toggleChartBtn" onclick="toggleChartType()">切换图表类型</button>
            </div>
            <div class="stats-box">
                <h3>答题统计</h3>
                <canvas id="statsChart" width="300" height="300"></canvas>
                <div id="answerStats" style="display: none;"></div>
            </div>
        </div>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io('/teacher'); // 连接教师端命名空间
        currentQuestion = null;
        currentChartType = 'bar'; // 初始图表类型为柱形图
        chartInstance = null; // 用于存储图表实例
        // 渲染统计结果
        function renderStats(stats) {
            if (!stats || Object.keys(stats).length === 0) return;
            
            // 确保统计值为整数
            const intStats = {};
            Object.keys(stats).forEach(key => {
                intStats[key] = Math.round(stats[key]);
            });
            
            const ctx = document.getElementById('statsChart').getContext('2d');
            if (chartInstance) chartInstance.destroy();
            
            chartInstance = new Chart(ctx, {
                type: currentChartType,
                data: {
                    labels: Object.keys(intStats),
                    datasets: [{
                        label: '答题人数',
                        data: Object.values(intStats),
                        backgroundColor: Object.keys(intStats).map((_, i) => `hsl(${i * 360 / Object.keys(intStats).length}, 70%, 60%)`),
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1,
                                callback: function(value) {
                                    if (Number.isInteger(value)) {
                                        return value;
                                    }
                                }
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = Math.round((context.raw / total) * 100);
                                    return `${percentage}% (${Math.round(context.raw)}人)`;
                                }
                            }
                        }
                    }
                }
            });
        }

        // 切换图表类型
        function toggleChartType() {
            currentChartType = currentChartType === 'bar' ? 'pie' : 'bar';
            if (chartInstance) {
                chartInstance.destroy();  // 确保销毁旧实例
                chartInstance = null;
            }
            if (currentStats) {
                renderStats(currentStats);  // 使用当前统计重新渲染
            }
        }

        // 初始化获取当前题目
        socket.on('currentQuestion', ({ question, isPublished, stats }) => {
            currentQuestion = question;
            renderQuestion(question, isPublished);
            if (stats) {
                renderStats(stats);  // 使用服务器发送的统计数据
            }
        });

        // 监听答题统计
        let currentStats = {};
        socket.on('answerStats', (stats) => {
            console.log('收到统计数据:', stats); // 添加这行调试日志
            currentStats = stats;
            renderStats(stats);
        });

        // 渲染题目
        function renderQuestion(question, isPublished) {
            const questionDiv = document.getElementById('currentQuestionDisplay');
            let optionsHtml = '';
            if (question.options) {
                optionsHtml = `<div class="options"><p>选项：${question.options.join('、')}</p></div>`;
            }
            questionDiv.innerHTML = `
                <h2>题目 ${question.id}</h2>
                <p>${question.question}</p>
                ${optionsHtml}
                <p>状态：${isPublished ? '已发布' : '未发布'}</p>
            `;
            document.getElementById('publishBtn').textContent = isPublished ? '收回题目' : '发布题目';
        }

        // 发布/收回题目
        function publishQuestion() {
            socket.emit('publishQuestion');
        }

        // 切换下一题
        function nextQuestion() {
            socket.emit('nextQuestion');
        }

        // 添加prevQuestion函数
        function prevQuestion() {
            socket.emit('prevQuestion');
        }
        
        // 发送工具链接到学生端
        function sendToolLink() {
            socket.emit('sendToolLink', {url: '/程序设计.html'});
        }

        // 在文件底部添加
        window.addEventListener('DOMContentLoaded', () => {
            const canvas = document.getElementById('statsChart');
            if (!canvas) {
                console.error('Canvas元素未找到');
            } else {
                console.log('Canvas元素已找到，尺寸:', canvas.width, 'x', canvas.height);
            }
        });
    </script>

</body>
</html>